<?php
include_once dirname(dirname(dirname(__FILE__))) . '/models/public_model_exec.class.php';
class child_c2_task_model
{		
	/**
	 * 获取图片FTP、http地址
	 * @param 图片路径 $img_path
	 * @param SPid $sp_id
	 */
	static public function get_image_url($img_path,$sp_id)
	{
		include_once dirname(dirname(dirname(__FILE__))).'/'.$sp_id.'/define.php';
		if(defined('HW_DOANLOAD_IMG_METHOD') && HW_DOANLOAD_IMG_METHOD=='ftp' && !empty($img_path))
		{
			//$img_path = strrchr($img_path,'/');
			$img_url = HW_DOANLOAD_IMG_FTP.$img_path;
		}
		else
		{
			$img_url = nl_image::epg_video_image_url($img_path);
		}
		return $img_url;
	}
	/**
	 * 获取任务名称
	 */	
	static public function get_task_name($task_id)
	{
		$db = nn_get_db(NL_DB_READ);
		$sql = "select nns_name from nns_mgtvbk_c2_task where nns_id='$task_id'";
		return nl_db_get_col($sql, $db);
	}

	/**
	 * 添加连续剧
	 */
	static public function add_series($vod_info,$sp_id)
	{
		$action = 'REGIST';
		return self::do_series($vod_info,$action,$sp_id);
	}
	/**
	 * 修改连续剧
	 */
	static public function update_series($vod_info,$sp_id)
	{
		$action = 'UPDATE';
		return self::do_series($vod_info,$action,$sp_id);
	}
	/**
	 * 连续剧剧头注入
	 * @param $vod_info 连续剧信息
	 * @param $action 操作
	 * @param $sp_id SPID
	 */
	static public function do_series($vod_info,$action,$sp_id)
	{
		//$vod_info 中包含vod信息，任务ID，任务名称
		$series_id = $vod_info['nns_id'];
        include_once dirname(dirname(__FILE__)).'/define.php';		
		if(empty($vod_info['nns_task_name']))
		{
			$vod_info['nns_task_name'] = self::get_task_name($vod_info['nns_task_id']);
		}		
		if(empty($vod_info['nns_name']))
		{
			$vod_info['nns_name'] = $vod_info['nns_task_name'];
		}
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
		$xml_str .= '<Objects>';	
		$sp_config = sp_model::get_sp_config($sp_id);
		$video_info = video_model::get_vod_info($series_id);
		$result_video_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'video', $series_id,$video_info,$sp_config);
		if($result_video_import_info['ret'] !=0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) < 1)
		{
			return false;
		}
		$vod_id = $result_video_import_info['data_info'];
		
		$xml_str .= '<Object ElementType="Series" ID="' .$vod_id. '" Action="' . $action . '" Code="' . $vod_id . '">';		
		$xml_str .= '<Property Name="Name">'.htmlspecialchars($vod_info['nns_name'],ENT_QUOTES).'HD</Property>';
		$xml_str .= '<Property Name="LicensingWindowStart">'. date('YmdHis').'</Property>';//有效开始时间(YYYYMMDDHH24MiSS)
		$xml_str .= '<Property Name="LicensingWindowEnd">'. date('YmdHis',time()+ 3*365*24*60*60).'</Property>';//有效结束时间(YYYYMMDDHH24MiSS)			
		$xml_str .= '<Property Name="OrderNumber"></Property>';//节目订购编号
		$xml_str .= '<Property Name="OriginalName">'.htmlspecialchars($vod_info['nns_alias_name'],ENT_QUOTES).'</Property>';//原名
		if(empty($vod_info['nns_eng_name']))
		{
			$vod_info['nns_eng_name'] = date('YmdHis');
		}
		$xml_str .= '<Property Name="SortName">'.htmlspecialchars($vod_info['nns_eng_name'],ENT_QUOTES).'</Property>';//索引名称供界面排序
		$xml_str .= '<Property Name="SearchName">'.$vod_info['nns_pinyin'].'</Property>';//搜索名称供界面搜索
		$xml_str .= '<Property Name="OrgAirDate">' . date('Ymd',strtotime($vod_info['nns_show_time'])).'</Property>';//首播日期(YYYYMMDD)
		$xml_str .= '<Property Name="DisplayAsNew"></Property>';//新到天数
		$xml_str .= '<Property Name="DisplayAsLastChance">300</Property>';//剩余天数
		$xml_str .= '<Property Name="Macrovision">0</Property>';//拷贝保护标志0:无拷贝保护    1:有拷贝保护
		$xml_str .= '<Property Name="Price"></Property>';//含税定价
		$xml_str .= '<Property Name="VolumnCount">'.$vod_info['nns_all_index'].'</Property>';//总集数
		$xml_str .= '<Property Name="Status">1</Property>';//状态标志,0:失效 1:生效
		$nns_summary = mb_strcut($vod_info['nns_summary'], 0,4000,'utf-8');
		$xml_str .= '<Property Name="Description">'.htmlspecialchars($nns_summary,ENT_QUOTES).'</Property>';//描述信息
		$xml_str .= '<Property Name="Kpeople">'.$vod_info['nns_actor'].'</Property>';//主要人物
		$xml_str .= '<Property Name="Director">'.$vod_info['nns_director'].'</Property>';//主要人物
		$xml_str .= '<Property Name="ScriptWriter"></Property>';//编剧
		$xml_str .= '<Property Name="Guest"></Property>';//受访者
		$xml_str .= '<Property Name="Reporter"></Property>';//记者
		$xml_str .= '<Property Name="OPIncharge"></Property>';//其他责任人
		$xml_str .= '<Property Name="Compere"></Property>';//节目主持人								
		$xml_str .= '</Object>';
		$pic_id = $series_id;
		if(empty($vod_info['nns_image2']) && !empty($vod_info['nns_image_v']))
		{
			$vod_info['nns_image2'] = $vod_info['nns_image_v'];
		}
		if(!empty($vod_info['nns_image2']))
		{
			$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image2']);
			$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
			if(file_exists($file_img))
			{										 
				$pic_url = self::get_image_url($img_save_name,$sp_id);
				$xml_str .= '<Object ElementType="Picture" ID="' .$pic_id. '" Code="' .$pic_id. '" Action="' . $action . '">';
				$xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
				$xml_str .= '<Property Name="Description"></Property>';//描述			
				$xml_str .= '</Object>';
			}		
		}		
		$xml_str .= '</Objects>';
		//$xml_str .= '<Mappings>';
		//栏目关系
		//$category_id = (!isset($vod_info['nns_category_id'][0]) || empty($vod_info['nns_category_id'][0])) ? $video_info['nns_category_id'] : $vod_info['nns_category_id'][0];
		//$xml_str .= '<Mapping ParentType="Category" ParentID="'.$category_id.'" ParentCode="'.$category_id.'" ElementType="Series" ElementID="'.$vod_id.'" ElementCode="'.$vod_id.'" Action="' . $action . '">';			
		//$xml_str .= '</Mapping>';
		//图片
	    if(!empty($vod_info['nns_image2']))
	    {
	    	$xml_str .= '<Mappings>';
			$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image2']);
			$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
			if(file_exists($file_img))
			{			
				$xml_str .= '<Mapping ParentType="Picture" ParentID="'.$pic_id.'" ParentCode="'.$pic_id.'" ElementType="Series" ElementID="'.$vod_id.'" ElementCode="'.$vod_id.'" Action="' . $action . '">';
				$xml_str .= '<Property Name="Type">1</Property>'; 			
				$xml_str .= '<Property Name="Sequence">0</Property>';			
				$xml_str .= '</Mapping>';						
			}
			$xml_str .= '</Mappings>';
	    }		
	    //$xml_str .= '</Mappings>';
		$xml_str .= '</ADI>';
		//die($xml_str);
		$file_name = 'series_'.$vod_id.'_'.$action.'.xml';
		$c2_info = array(
			'nns_task_type'=>'Series',
			'nns_task_id'=> isset($vod_info['nns_task_id']) ? $vod_info['nns_task_id'] : null,	
			'nns_task_name'=> isset($vod_info['nns_task_name']) ? $vod_info['nns_task_name'] : null,	
			'nns_action'=>	$action,		
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Series,'.$action,
		);		
		return self::execute_c2($c2_info,$sp_id);		
	}	
	/**
	 * @params array(
	 * nns_id
	 * nns_task_id
	 * )
	 */
	static public function delete_series($params,$sp_id)
	{	
		include dirname(dirname(__FILE__)).'/define.php';
		$action = "DELETE";
		$sp_config = sp_model::get_sp_config($sp_id);
		$series_id = $params['nns_id'];
		$video_info = video_model::get_vod_info($params['nns_id']);
		$result_video_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'video', $series_id,$video_info,$sp_config);
		if($result_video_import_info['ret'] !=0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) < 1)
		{
			return false;
		}
		$series_id = $result_video_import_info['data_info'];			
		$xml_str .= '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Series" ID="' .$series_id. '" Action="' . $action . '" Code="' . $series_id . '"></Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
		//die($xml_str);
		//$guid = np_guid_rand();
		$file_name = 'series_'.$series_id.'_'.$action.'.xml';
		
		$c2_info = array(
			'nns_task_type'=>'Series',
			'nns_task_id'=>  isset($params['nns_task_id'])?$params['nns_task_id']:null,	
			'nns_task_name'=>  isset($params['nns_task_name'])?$params['nns_task_name']:null,	
			'nns_action'=>	$action,		
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Series,'.$action,
		);		
		return self::execute_c2($c2_info,$sp_id);
	}
	/**
	 * 添加分集
	 */
	static public function add_vod($index_info,$sp_id)
	{
		$action = 'REGIST';
		return self::do_vod($index_info,$sp_id,$action);
	}
	/**
	 * 修改分集
	 */
	static public function update_vod($index_info,$sp_id)
	{
		$action = 'UPDATE';
		return self::do_vod($index_info,$sp_id,$action);
	}
	/**
	 * 分集注入
	 */
   	static public function do_vod($index_info,$sp_id,$action)
   	{
   		include_once dirname(dirname(__FILE__)) . '/define.php';
        $program_id = $index_info['nns_id'];
        $sp_config = sp_model::get_sp_config($sp_id);
        if(isset($index_info['nns_series_flag']) && $index_info['nns_series_flag'] == 1)
        {
	        $video_index_info = video_model::get_vod_index_info($program_id);
	     	$result_index_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'index', $program_id,$video_index_info,$sp_config);
			if($result_index_import_info['ret'] !=0 || !isset($result_index_import_info['data_info']) || strlen($result_index_import_info['data_info']) <1)
			{
			    return false;
			}
			$vod_index_id = $result_index_import_info['data_info'];
        }
        else 
        {
        	$video_info = video_model::get_vod_info($program_id);
			$result_video_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'video', $program_id,$video_info,$sp_config);
			if($result_video_import_info['ret'] !=0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) < 1)
			{
				return false;
			}
			$vod_index_id = $result_video_import_info['data_info'];
        }
        $xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
        $xml_str .= '<Objects>';
    
        $xml_str .= '<Object ElementType="Program" ID="' .$vod_index_id. '" Action="' . $action . '" Code="' .$vod_index_id. '">';
    
        if(empty($index_info['nns_task_name']))
        {
            $index_info['nns_task_name'] = self::get_task_name($index_info['nns_task_id']);
        }
        if(empty($index_info['nns_name']))
        {
            $index_info['nns_name'] = $index_info['nns_task_name'];
        }
    
        $xml_str .= '<Property Name="Name">'.htmlspecialchars($index_info['nns_name'],ENT_QUOTES).'HD</Property>';
        $xml_str .= '<Property Name="OrderNumber"></Property>';//节目订购编号
        $xml_str .= '<Property Name="OriginalName">'.htmlspecialchars($index_info['nns_alias_name'],ENT_QUOTES).'</Property>';//原名
        $xml_str .= '<Property Name="SortName"></Property>';//索引名称供界面排序
        $xml_str .= '<Property Name="SearchName">'.$index_info['nns_pinyin'].'</Property>';//搜索名称供界面搜索
        $xml_str .= '<Property Name="ActorDisplay">'.htmlspecialchars($index_info['nns_actor'],ENT_QUOTES).'</Property>';//演员列表(只供显示)
        $xml_str .= '<Property Name="WriterDisplay">'.htmlspecialchars($index_info['nns_director'],ENT_QUOTES).'</Property>';//作者列表(只供显示)
        $xml_str .= '<Property Name="OriginalCountry">'.htmlspecialchars($index_info['nns_area'],ENT_QUOTES).'</Property>';//国家地区
        $xml_str .= '<Property Name="Language">'.htmlspecialchars($index_info['nns_language'],ENT_QUOTES).'</Property>';//语言
        $show_time = null;
        if($index_info['nns_index_show_time']=='0000-00-00 00:00:00' || empty($index_info['nns_index_show_time']))
        {
            $show_time = $index_info['nns_show_time'];//影片基本信息上的上映时间
        }
        else
        {
            $show_time = $index_info['nns_index_show_time'];//分集的上映时间
        }
    
        $xml_str .= '<Property Name="ReleaseYear">' .  date('Y',strtotime($show_time)).'</Property>';//上映年份(YYYY)
        $xml_str .= '<Property Name="OrgAirDate">' . date('Ymd',strtotime($show_time)).'</Property>';//首播日期(YYYYMMDD)
        $xml_str .= '<Property Name="LicensingWindowStart">'. date('YmdHis').'</Property>';//有效开始时间(YYYYMMDDHH24MiSS)
        $xml_str .= '<Property Name="LicensingWindowEnd">'. date('YmdHis',time()+ 3*365*24*60*60).'</Property>';//有效结束时间(YYYYMMDDHH24MiSS)
        $xml_str .= '<Property Name="DisplayAsNew">0</Property>';//新到天数
        $xml_str .= '<Property Name="DisplayAsLastChance">300</Property>';//剩余天数
        $xml_str .= '<Property Name="Macrovision">0</Property>';//拷贝保护标志0:无拷贝保护	1:有拷贝保护
		$xml_str .= '<Property Name="Description">'.mb_substr(htmlspecialchars($index_info['nns_summary'],ENT_QUOTES),0,400,'utf-8').'</Property>';//描述信息
        $xml_str .= '<Property Name="PriceTaxIn"></Property>';//列表定价
        $xml_str .= '<Property Name="Status">1</Property>';//状态标志 0:失效 1:生效
        $xml_str .= '<Property Name="SourceType">1</Property>';//1: VOD 5: Advertisement
        $xml_str .= '<Property Name="SeriesFlag">'.$index_info['nns_series_flag'].'</Property>';//0: 普通VOD 1: 连续剧剧集
    
        $xml_str .= '<Property Name="Kpeople">'.htmlspecialchars($index_info['nns_actor'],ENT_QUOTES).'</Property>';//关键字 多个关键字之间使用分号分隔
        $xml_str .= '<Property Name="Director">'.htmlspecialchars($index_info['nns_director'],ENT_QUOTES).'</Property>';//关联标签 多个标签之间使用分号分隔
        $xml_str .= '<Property Name="ScriptWriter"></Property>';//编剧
		$xml_str .= '<Property Name="Guest"></Property>';//受访者
		$xml_str .= '<Property Name="Reporter"></Property>';//记者
		$xml_str .= '<Property Name="OPIncharge"></Property>';//其他责任人
		$xml_str .= '<Property Name="Compere"></Property>';//节目主持人	  
        $xml_str .= '</Object>';
        //echo '<pre>';var_dump($index_info);die;
        if(isset($index_info['nns_series_flag']) && $index_info['nns_series_flag'] == 1 && !empty($index_info['nns_image']))
        {
        	$img_save_name = str_replace('.JPG','.jpg',$index_info['nns_image']);
        	$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
        	if(file_exists($file_img))
        	{
	            $pic_url = self::get_image_url($img_save_name,$sp_id);
	            $xml_str .= '<Object ElementType="Picture" ID="' .$program_id. '" Action="' . $action . '" Code="' .$program_id. '">';
	            $xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
	            $xml_str .= '<Property Name="Description"></Property>';//描述
	            $xml_str .= '</Object>';
        	}
		}
		elseif (isset($index_info['nns_series_flag']) && $index_info['nns_series_flag'] == 0)
		{
			if(!empty($index_info['nns_image_v']))
			{
				$index_info['nns_image2'] = $index_info['nns_image_v'];
			}
            if(!empty($index_info['nns_image2']))
            {
   				$img_save_name = str_replace('.JPG','.jpg',$index_info['nns_image2']);
                $file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
                if(file_exists($file_img))
                {
                	$pic_url = self::get_image_url($img_save_name,$sp_id);
                    $xml_str .= '<Object ElementType="Picture" ID="' .$program_id. '" Action="' . $action . '" Code="' .$program_id. '">';
                    $xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
                   	$xml_str .= '<Property Name="Description"></Property>';//描述
                    $xml_str .= '</Object>';
				}
         	}
      	}
    
        $xml_str .= '</Objects>';
        $xml_str .= '<Mappings>';

        //如果是连续剧分集，绑定到连续剧
        if(isset($index_info['nns_series_flag']) && $index_info['nns_series_flag'] == 1)
        {
            $vod_id = $index_info['nns_vod_id'];
            $vod_info = video_model::get_vod_info($vod_id);
            $result_video_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'video', $vod_id,$vod_info,$sp_config);
            if($result_video_import_info['ret'] !=0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) <1)
            {
            	return false;
            }
            $vod_id = $result_video_import_info['data_info'];
    
            $sequence = $index_info['nns_index'] + 1;
            $xml_str .= '<Mapping ParentType="Series" ParentID="'.$vod_id.'" ElementType="Program" ElementID="'.$vod_index_id.'" ParentCode="'.$vod_id.'" ElementCode="'.$vod_index_id.'" Action="REGIST">';
            $xml_str .= '<Property Name="Sequence">'.$sequence.'</Property>';//
            $xml_str .= '</Mapping>';
    
            if(!empty($index_info['nns_image']))
            {
            	$img_save_name = str_replace('.JPG','.jpg',$index_info['nns_image']);
            	$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
            	if(file_exists($file_img))
            	{
	            	$xml_str .= '<Mapping ParentType="Picture" ParentID="'.$program_id.'" ElementType="Program" ElementID="'.$vod_index_id.'" ParentCode="'.$program_id.'" ElementCode="'.$vod_index_id.'" Action="' . $action . '">';
	            	//Picture时：0: 缩略图 1: 海报 2: 剧照 3: 图标 4: 标题图 5: 广告图 6: 草图 7: 背景图 9: 频道图片
	            	//10: 频道黑白图片 11: 频道Logo 12: 频道名字图片99: 其他
	            	$xml_str .= '<Property Name="Type">1</Property>';
	            	$xml_str .= '<Property Name="Sequence">0</Property>';//
	            	$xml_str .= '</Mapping>';
            	}
            }
        }
        else
        {
        	//栏目关系
        	if(!empty($index_info['nns_category_id']) && isset($index_info['nns_category_id'][0]))
        	{
        		$category_id = $index_info['nns_category_id'][0];
        	}
        	else
        	{
        		$category_id = $video_info['nns_category_id'];
        	}
        	 
        	//$xml_str .= '<Mapping ParentType="Category" ParentID="'.$category_id.'" ElementType="Program" ElementID="'.$vod_index_id.'" ParentCode="'.$category_id.'" ElementCode="'.$vod_index_id.'" Action="' . $action . '">';
        	//$xml_str .= '</Mapping>';
        	if(!empty($index_info['nns_image_v']))
        	{
        		$index_info['nns_image2'] = $index_info['nns_image_v'];
        	}
        	if(!empty($index_info['nns_image2']))
        	{
            	$img_save_name = str_replace('.JPG','.jpg',$index_info['nns_image2']);
               	$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
                if(file_exists($file_img))
                {
                	$xml_str .= '<Mapping ParentType="Picture" ParentID="'.$program_id.'" ElementType="Program" ElementID="'.$vod_index_id.'" ParentCode="'.$program_id.'" ElementCode="'.$vod_index_id.'" Action="' . $action . '">';
                    //Picture时：0: 缩略图 1: 海报 2: 剧照 3: 图标 4: 标题图 5: 广告图 6: 草图 7: 背景图 9: 频道图片
                    //10: 频道黑白图片 11: 频道Logo 12: 频道名字图片99: 其他
                    $xml_str .= '<Property Name="Type">1</Property>';
                    $xml_str .= '<Property Name="Sequence">0</Property>';//
                    $xml_str .= '</Mapping>';
                 }
            }
         }
        $xml_str .= '</Mappings>';
        $xml_str .= '</ADI>';
        //die($xml_str);
        $file_name = 'program_'.$vod_index_id.'_'.$action.'.xml';
        $c2_info = array(
        		'nns_task_type'=>'Program',
        		'nns_task_id'=> isset($index_info['nns_task_id']) ? $index_info['nns_task_id'] : null,
        		'nns_task_name'=> isset($index_info['nns_task_name']) ? $index_info['nns_task_name'] : null,
        		'nns_action'=>	$action,
        		'nns_url' => $file_name,
        		'nns_content' => $xml_str,
        		'nns_desc' => 'Program,'.$action,
        );    
        return self::execute_c2($c2_info,$sp_id);
    }
    /**
     * 删除分集
     * @param $vod_info 为主媒资ID信息
     */
    static public function delete_vod($index_info,$sp_id)
    {
    	$action = 'DELETE';
        $sp_config = sp_model::get_sp_config($sp_id);
        if($index_info['nns_type'] === 'video') //电影删除
        {
        	$video_info = video_model::get_vod_info($index_info['nns_id']);
        	
        	$result_video_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'video', $index_info['nns_id'],$video_info,$sp_config);
        	if($result_video_import_info['ret'] !=0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) < 1)
        	{
        		return false;
        	}
        	$vod_index_id = $result_video_import_info['data_info'];
        }
        else 
        {
        	$video_index_info = video_model::get_vod_index_info($index_info['nns_id']);
        	
        	$result_video_index_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'index', $index_info['nns_id'],$video_index_info,$sp_config);
        	if($result_video_index_import_info['ret'] !=0 || !isset($result_video_index_import_info['data_info']) || strlen($result_video_index_import_info['data_info']) < 1)
        	{
        		return false;
        	}
        	$vod_index_id = $result_video_index_import_info['data_info'];      	
        }
		
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Program" ID="' .$vod_index_id. '" Action="' . $action . '" Code="' .$vod_index_id. '">';
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
		$file_name = 'program' .'_'. $vod_index_id . '_' . $action . '.xml';
		//die($xml_str);
		$c2_info = array(
			'nns_task_type'=>'Program',
			'nns_task_id'=> isset($index_info['nns_task_id']) ? $index_info['nns_task_id']:null,
			'nns_task_name'=> isset($index_info['nns_task_name']) ? $index_info['nns_task_name']:null,
			'nns_action'=>	$action,
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Program,'.$action,
		);
		return self::execute_c2($c2_info,$sp_id);
    }
	/**
	 * 创建VOD信息
	 * @param 片源信息  $index_media
	 * @param 操作 $action
	 * @param SPID $sp_id
	 */
	static public function build_vod($index_media,$action,$sp_id)
	{
		include_once dirname(dirname(__FILE__)).'/define.php';	
	    //获取这个影片的主媒资ID,查询这个媒资是电影还是连续剧
        $is_series = false;
        $vod_info = video_model::get_vod_info($index_media['nns_video_id']);     
        $vod_index_info = video_model::get_vod_index_info($index_media['nns_video_index_id']);     
        $nns_task_name = $index_media['nns_task_name'];           
        $vod_index_info['nns_series_flag'] = 0;
        if($vod_info['nns_all_index'] > 1)
        {//连续剧
            $is_series = true;
            $vod_index_info['nns_series_flag'] = 1;
            $index_ex = video_model::get_vod_ex_info($vod_index_info['nns_import_id'],'index');
        }
        else
        {//影片
            $vod_index_info['nns_name'] = $vod_info['nns_name'];
            $vod_index_info['nns_series_flag'] = 0;
            $vod_ex = video_model::get_vod_ex_info($vod_info['nns_asset_import_id']);
        }

		//获取SP配置
		$sp_config = sp_model::get_sp_config($sp_id);
		if($is_series) //电视剧
        {
	     	$result_index_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'index', $index_media['nns_video_index_id'],$vod_index_info,$sp_config);
			if($result_index_import_info['ret'] !=0 || !isset($result_index_import_info['data_info']) || strlen($result_index_import_info['data_info']) <1)
			{
			    return false;
			}
			$vod_index_id = $result_index_import_info['data_info'];
        }
        else 
        {
			$result_video_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'video', $index_media['nns_video_id'],$vod_info,$sp_config);
			if($result_video_import_info['ret'] !=0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) < 1)
			{
				return false;
			}
			$vod_index_id = $result_video_import_info['data_info'];
        }
								
		if(!empty($vod_index_info['nns_name']) && $is_series)
		{
			$vod_info['nns_name'] = $vod_index_info['nns_name'];
		}
		if($is_series)
		{
			$vod_info['nns_alias_name'] = $index_ex['subordinate_name'];
		}

		if(!$is_series)//电影取主媒资的数据
		{
			$vod_index_info['nns_actor'] = !empty($vod_info['nns_actor']) ? $vod_info['nns_actor'] : $vod_index_info['nns_actor'];
			$vod_index_info['nns_director'] = !empty($vod_info['nns_director']) ? $vod_info['nns_director'] : $vod_index_info['nns_director'];
			$vod_index_info['nns_area'] = $vod_info['nns_area'];
			$vod_index_info['nns_language']= $vod_info['nns_language'];
			$vod_info['nns_index_show_time'] = empty($vod_info['nns_index_show_time']) ? $vod_info['nns_show_time'] : $vod_index_info['nns_release_time'];
			$vod_index_info['nns_summary'] = $vod_info['nns_summary'];
		}	
		
		if(empty($vod_index_info['nns_actor']))
		{
			$vod_index_info['nns_actor'] = $vod_info['nns_play_role'];
		}
		if(empty($vod_index_info['nns_director']))
		{
			$vod_index_info['nns_director'] = $vod_info['nns_play_role'];
		}
		$actor = str_replace(array('|',' ','/'), ',', $vod_index_info['nns_actor']);
		$director = str_replace(array('|',' ','/'), ',', $vod_index_info['nns_director']);
		$area = str_replace(array('|',' ','/'), ',', $vod_index_info['nns_area']);
		$language = str_replace(array('|',' ','/'), ',', $vod_index_info['nns_language']);
		$show_time = null;
		if($vod_info['nns_index_show_time'] == '0000-00-00 00:00:00' || empty($vod_info['nns_index_show_time']))
		{
			$show_time = $vod_info['nns_show_time'];//影片基本信息上的上映时间
		}
		else
		{
			$show_time = $vod_info['nns_index_show_time'];//分集的上映时间
		}
			
		$xml_str = '<Object ElementType="Program" ID="' .$vod_index_id. '" Action="' . $action . '" Code="' .$vod_index_id. '">';
		$xml_str .= '<Property Name="Name">'.htmlspecialchars($vod_info['nns_name'],ENT_QUOTES).'HD</Property>';
		$xml_str .= '<Property Name="OrderNumber"></Property>';//节目订购编号
		$xml_str .= '<Property Name="OriginalName">'.htmlspecialchars($vod_info['nns_alias_name'],ENT_QUOTES).'</Property>';//原名
		$xml_str .= '<Property Name="SortName"></Property>';//索引名称供界面排序
		$xml_str .= '<Property Name="SearchName">'.$vod_info['nns_pinyin'].'</Property>';//搜索名称供界面搜索
		$xml_str .= '<Property Name="ActorDisplay">'.htmlspecialchars($actor,ENT_QUOTES).'</Property>';//演员列表(只供显示)
		$xml_str .= '<Property Name="WriterDisplay">'.htmlspecialchars($director,ENT_QUOTES).'</Property>';//作者列表(只供显示)
		$xml_str .= '<Property Name="OriginalCountry">'.htmlspecialchars($area,ENT_QUOTES).'</Property>';//国家地区
		$xml_str .= '<Property Name="Language">'.htmlspecialchars($language,ENT_QUOTES).'</Property>';//语言		
		$xml_str .= '<Property Name="ReleaseYear">' .  date('Y',strtotime($show_time)).'</Property>';//上映年份(YYYY)
		$xml_str .= '<Property Name="OrgAirDate">' . date('Ymd',strtotime($show_time)).'</Property>';//首播日期(YYYYMMDD)
		$xml_str .= '<Property Name="LicensingWindowStart">'. date('YmdHis').'</Property>';//有效开始时间(YYYYMMDDHH24MiSS)
		$xml_str .= '<Property Name="LicensingWindowEnd">'. date('YmdHis',time()+ 3*365*24*60*60).'</Property>';//有效结束时间(YYYYMMDDHH24MiSS)
		$xml_str .= '<Property Name="DisplayAsNew">0</Property>';//新到天数
		$xml_str .= '<Property Name="DisplayAsLastChance">300</Property>';//剩余天数
		$xml_str .= '<Property Name="Macrovision">0</Property>';//拷贝保护标志0:无拷贝保护	1:有拷贝保护
		$xml_str .= '<Property Name="Description">'.mb_substr(htmlspecialchars($vod_index_info['nns_summary'],ENT_QUOTES),0,400,'utf-8').'</Property>';//描述信息
		$xml_str .= '<Property Name="PriceTaxIn"></Property>';//列表定价
		$xml_str .= '<Property Name="Status">1</Property>';//状态标志 0:失效 1:生效
		$xml_str .= '<Property Name="SourceType">1</Property>';//1: VOD 5: Advertisement
		$xml_str .= '<Property Name="SeriesFlag">'.$vod_index_info['nns_series_flag'].'</Property>';//0: 普通VOD 1: 连续剧剧集	
		$xml_str .= '<Property Name="Kpeople">'.htmlspecialchars($actor,ENT_QUOTES).'</Property>';//关键字 多个关键字之间使用分号分隔
		$xml_str .= '<Property Name="Director">'.htmlspecialchars($director,ENT_QUOTES).'</Property>';//关联标签 多个标签之间使用分号分隔
		$xml_str .= '<Property Name="ScriptWriter"></Property>';//编剧
		$xml_str .= '<Property Name="Guest"></Property>';//受访者
		$xml_str .= '<Property Name="Reporter"></Property>';//记者
		$xml_str .= '<Property Name="OPIncharge"></Property>';//其他责任人
		$xml_str .= '<Property Name="Compere"></Property>';//节目主持人
		$xml_str .= '</Object>';
		$map_xml_str = '';
		if(!$is_series) //电影
		{
			if(!empty($vod_info['nns_image_v']))
			{
				$vod_info['nns_image2'] = $vod_info['nns_image_v'];
			}
			if(!empty($vod_info['nns_image2']))
			{
				$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image2']);
				$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
				if(file_exists($file_img))
				{
					$pic_url = self::get_image_url($img_save_name,$sp_id);
					$xml_str .= '<Object ElementType="Picture" ID="' .$vod_index_id. '" Action="' . $action . '" Code="' .$vod_index_id. '">';
					$xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
					$xml_str .= '<Property Name="Description"></Property>';//描述
					$xml_str .= '</Object>';
					
					$map_xml_str .= '<Mapping ParentType="Picture" ParentID="'.$vod_index_id.'" ElementType="Program" ElementID="'.$vod_index_id.'" ParentCode="'.$vod_index_id.'" ElementCode="'.$vod_index_id.'" Action="' . $action . '">';
					//Picture时：0: 缩略图 1: 海报 2: 剧照 3: 图标 4: 标题图 5: 广告图 6: 草图 7: 背景图 9: 频道图片
					//10: 频道黑白图片 11: 频道Logo 12: 频道名字图片99: 其他
					$map_xml_str .= '<Property Name="Type">1</Property>';
					$map_xml_str .= '<Property Name="Sequence">0</Property>';//
					$map_xml_str .= '</Mapping>';
				}
			}
		}
		else 
		{
			$result_video_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'video', $index_media['nns_video_id'],$vod_info,$sp_config);
			if($result_video_import_info['ret'] !=0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) <1)
			{
				return false;
			}
			$vod_id = $result_video_import_info['data_info'];
			
			$sequence = $vod_index_info['nns_index'] + 1;
			$map_xml_str .= '<Mapping ParentType="Series" ParentID="'.$vod_id.'" ElementType="Program" ElementID="'.$vod_index_id.'" ParentCode="'.$vod_id.'" ElementCode="'.$vod_index_id.'" Action="'.$action.'">';
			$map_xml_str .= '<Property Name="Sequence">'.$sequence.'</Property>';//
			$map_xml_str .= '</Mapping>';
			
			if(!empty($vod_index_info['nns_image']))
			{
				$img_save_name = str_replace('.JPG','.jpg',$vod_index_info['nns_image']);
				$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
				if(file_exists($file_img))
				{
					$pic_url = self::get_image_url($img_save_name,$sp_id);
					$xml_str .= '<Object ElementType="Picture" ID="' .$vod_index_id. '" Action="' . $action . '" Code="' .$vod_index_id. '">';
					$xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
					$xml_str .= '<Property Name="Description"></Property>';//描述
					$xml_str .= '</Object>';
					
					$map_xml_str .= '<Mapping ParentType="Picture" ParentID="'.$vod_index_id.'" ElementType="Program" ElementID="'.$vod_index_id.'" ParentCode="'.$vod_index_id.'" ElementCode="'.$vod_index_id.'" Action="' . $action . '">';
					//Picture时：0: 缩略图 1: 海报 2: 剧照 3: 图标 4: 标题图 5: 广告图 6: 草图 7: 背景图 9: 频道图片
					//10: 频道黑白图片 11: 频道Logo 12: 频道名字图片99: 其他
					$map_xml_str .= '<Property Name="Type">1</Property>';
					$map_xml_str .= '<Property Name="Sequence">0</Property>';
					$map_xml_str .= '</Mapping>';
				}
			}	
		}		
		$xml_info = array(
			'object_xml' => $xml_str,
			'mapping_xml' => $map_xml_str,
		);		
		return $xml_info;
	}	
	/**
	 * 注入片源（以分集为单位,切片完成后调用）
	 * $index_media array(
	 * 			'nns_video_id'
	 * 			'nns_video_index_id'
	 * 			'nns_task_id'
	 * 			'nns_new_dir'
	 * 			'nns_media_ids'
	 * )
	 */
	static public function add_movies_by_vod_index($index_media,$sp_id)
	{
		include dirname(dirname(__FILE__)).'/define.php';
		$db = nn_get_db(NL_DB_WRITE);
		$sp_config = sp_model::get_sp_config($sp_id);
		$video_info = video_model::get_vod_info($index_media['nns_video_id']);
		if($video_info['nns_all_index'] > 1)//连续剧的单集片源
		{
			$video_index_info = video_model::get_vod_index_info($index_media['nns_video_index_id']);
			$result_index_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'index', $index_media['nns_video_index_id'],$video_index_info,$sp_config);
			if($result_index_import_info['ret'] !=0 || !isset($result_index_import_info['data_info']) || strlen($result_index_import_info['data_info']) <1)
			{
				return false;
			}
			$video_index_id = $result_index_import_info['data_info'];
		}
		else //电影片源
		{
			$result_video_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'video', $index_media['nns_video_id'],$video_info,$sp_config);
			if($result_video_import_info['ret'] !=0 || !isset($result_video_import_info['data_info']) || strlen($result_video_import_info['data_info']) < 1)
			{
				return false;
			}
			$video_index_id = $result_video_import_info['data_info'];
		}
		
		$action = 'REGIST';
		$sql = "select * from nns_vod_media where nns_deleted != 1 and nns_vod_id='{$index_media['nns_video_id']}' and nns_vod_index_id='{$index_media['nns_video_index_id']}' and nns_id='{$index_media['nns_media_id']}' order by nns_kbps desc limit 1";
		
		$medias = nl_db_get_all($sql,$db);
		if(is_array($medias) && count($medias) > 0)
		{
			$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
			
			$media_id = $index_media['nns_media_id'];
			$video_media_info = video_model::get_vod_media_info($media_id);
			$result_media_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'media', $media_id,$video_media_info,$sp_config);
			if($result_media_import_info['ret'] !=0 || !isset($result_media_import_info['data_info']) || strlen($result_media_import_info['data_info']) <1)
			{
				return false;
			}
			$video_media_id = $result_media_import_info['data_info'];
			
			$xml_str .= '<Objects>';
			$xml_arr = self::build_vod($index_media, $action, $sp_id);
			if($xml_arr === false)
			{
				return false;
			}
			$xml_str .= $xml_arr['object_xml'];
			$media = $medias[0];
			if((int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
			{				
				//判断片源的URL	
				if(empty($index_media['nns_date']))
				{
					$index_media['nns_date'] = nl_db_get_col("select nns_date from nns_mgtvbk_clip_task where nns_id='{$index_media['nns_clip_task_id']}'", $db);
				}		
				$url = MOVIE_FTP.$index_media['nns_date'].'/'.$index_media['nns_clip_task_id'].'/'.$video_info['nns_pinyin'].'-'.$media['nns_vod_index'].'.m3u8';
				if(!empty($index_media['nns_file_path']))
				{
					$url = MOVIE_FTP.$index_media['nns_file_path'];
				}
				//$bool = self::check_ftp_file($url,$sp_config);
				$bool = array('ret' => 0);
				//-->start 优化检查ftp文件的返回信息说明 <author:feijian.gao date:2017-1-19>
				switch($bool['ret'])
				{
					case 0: //文件存在，查询成功
						break;
					case 1: //ftp连接失败
						nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=10 where nns_id='{$index_media['nns_task_id']}'", $db);
						break;
					case 2: //文件不存在
						nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=11 where nns_id='{$index_media['nns_task_id']}'", $db);
						break;
					case 3: //获取文件列表失败
						nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=11 where nns_id='{$index_media['nns_task_id']}'", $db);
						break;
				}
				//获取切片后的片源文件失败，是否重新进行切片
				if($bool['ret'] != 0 && $sp_config['clip_file_repeat_enable'] != 0)
				{
					DEBUG && i_write_log_core('path_fail----'.$url,$sp_id.'/path_fail');
					include_once 'queue_task_model.php';
					$queue_task_model = new queue_task_model();
					$queue_task_model->q_re_clip($index_media['nns_task_id']);
					$queue_task_model=null;
					return false;
				}
				//--end
			}
			else 
			{
				if(strpos($medias[0]['nns_url'],'http://') === false || strpos($medias[0]['nns_url'],'ftp://') === false)
				{
					$url = rtrim(MOVIE_FTP,'/') . '/'. ltrim($medias[0]['nns_url'],'/');
				}
				else
				{
					$url = $medias[0]['nns_url'];
				}
			}
			$xml_str .= '<Object ElementType="Movie" ID="' .$video_media_id. '" Action="' . $action . '" Code="' .$video_media_id. '" >';
			$xml_str .= '<Property Name="Type">1</Property>';//媒体类型1:正片 2:预览片
			$xml_str .= '<Property Name="FileURL">' .$url. '</Property>';//媒体文件URL,ftp://username:password@ip:port/...  标准FTP协议
			$xml_str .= '<Property Name="SourceDRMType">0</Property>';//0: No DRM 1: BES DRM
			$xml_str .= '<Property Name="DestDRMType">0</Property>';//
			$xml_str .= '<Property Name="AudioType">1</Property>';//0: 其他 1: Monaural 单声道 2: Stereo 多声道 3: Two-nation monaural 双单声道 4: Two-nation stereo 双多声道  5: AC3(5:1 channel) AC3声道
			$xml_str .= '<Property Name="ClosedCaptioning">1</Property>';//0:无字幕 1:有字幕
			$xml_str .= '<Property Name="ScreenFormat"></Property>';
			$xml_str .= '</Object>';
			$xml_str .= '</Objects>';
			
			$xml_str .= '<Mappings>';
			$xml_str .= $xml_arr['mapping_xml'];
			$xml_str .= '<Mapping ParentType="Program" ParentID="'.$video_index_id.'" ElementType="Movie" ElementID="'.$video_media_id.'" ParentCode="'.$video_index_id.'" ElementCode="'.$video_media_id.'" Action="'.$action.'">';
			$xml_str .= '</Mapping>';	
			$xml_str .= '</Mappings>';	
			$xml_str .= '</ADI>';
			
			//die($xml_str);
			$file_name = 'movie_'. $video_media_id . '_'. $action . '.xml';
			
			$c2_info = array(
				'nns_task_type'=>'Movie',
				'nns_task_id'=> isset($index_media['nns_task_id'])?$index_media['nns_task_id']:null,
				'nns_task_name'=> isset($index_media['nns_task_name'])?$index_media['nns_task_name']:null,	
				'nns_action'=>	$action,
				'nns_url' => $file_name,
				'nns_content' => $xml_str,
				'nns_desc' => 'Movie,'.$action,
			);	
			if((int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
			{
				//修改切片的状态
				$clip_task_id = $index_media['nns_clip_task_id'];	
				//更改状态
				$dt = date('Y-m-d H:i:s');
				$set_state = array(
					'nns_state' => clip_task_model::TASK_C_STATE_C2_HANDLE,
					'nns_desc' => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_HANDLE],
					'nns_modify_time'=>$dt,
				);
				clip_task_model::update_task($clip_task_id, $set_state);
		
				//任务日志	
				$task_log = array(
					'nns_task_id' => $clip_task_id,
					'nns_state'   => clip_task_model::TASK_C_STATE_C2_HANDLE,
					'nns_desc'	=> clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_HANDLE],
				);	
				clip_task_model::add_task_log($task_log);
			}
			return self::execute_c2($c2_info,$sp_id);

		}
		else //片源已被删除 取消任务
		{
			DEBUG && i_write_log_core('--没有片源--');
			nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=7,nns_epg_status=100 where nns_id='{$index_media['nns_task_id']}'", $db);
		}	
	}	
	/**
	 * 删除影片
	 * params array(
	 * nns_id,
	 * nns_task_id
	 * )
	 */
	static public function delete_movie($index_media,$sp_id)
	{
		include_once dirname(dirname(__FILE__)).'/define.php';
		$action = 'DELETE';
		$sp_config = sp_model::get_sp_config($sp_id);
		$media_id = $index_media['nns_id'];
		$video_media_info = video_model::get_vod_media_info($media_id);
		$result_media_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'media', $media_id,$video_media_info,$sp_config);
		if($result_media_import_info['ret'] !=0 || !isset($result_media_import_info['data_info']) || strlen($result_media_import_info['data_info']) <1)
		{
			return false;
		}
		$video_media_id = $result_media_import_info['data_info'];

		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Movie" ID="' .$video_media_id. '" Action="' . $action . '" Code="' .$video_media_id. '">';	
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
		//die($xml_str);
		$file_name = 'movie_'. $video_media_id . '_'. $action . '.xml';
	
		$c2_info = array(
			'nns_task_type'=>'Movie',
			'nns_task_id'=> isset($index_media['nns_task_id']) ? $index_media['nns_task_id'] : null,	
			'nns_task_name'=> isset($index_media['nns_task_name']) ? $index_media['nns_task_name'] : null,
			'nns_action'=>	$action,
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Movie,'.$action,
		);
	
		//更改状态
		$dt = date('Y-m-d H:i:s');
		$set_state = array(
			'nns_state' => clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE,
			'nns_desc' => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE],
			'nns_modify_time'=>$dt,
		);
		clip_task_model::update_task($params['nns_clip_task_id'], $set_state);
								
		//任务日志	
		$task_log = array(
			'nns_task_id' => $params['nns_clip_task_id'],
			'nns_state'   => clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE,
			'nns_desc'	=> clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE],
		);	
		clip_task_model::add_task_log($task_log);
		return self::execute_c2($c2_info,$sp_id);	
	}
	/**
	 * 添加内容栏目
	 */
	static public function add_categoy($category_info,$sp_id)
	{
		$action = 'REGIST';
		return self::do_category($category_info,$action,$sp_id);
	}
	/**
	 * 修改内容栏目
	 */	
	static public function update_category($category_info,$sp_id)
	{
		$action = 'UPDATE';
		return self::do_category($category_info,$action,$sp_id);
	}
	/**
	 * 删除栏目
	 */
	static public function delete_category($param,$sp_id)
	{		
		include_once dirname(dirname(__FILE__)).'/define.php';
		$category_id = $param['nns_id'];
		$action = "DELETE";
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Category" ID="' .$category_id. '" Action="' . $action . '" Code="'.$category_id.'">';
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
				
		$file_name = 'category_'.$category_id.'_'.$action.'.xml';

		
		$c2_info = array(
			'nns_task_type'=>'Category',
			'nns_task_id'=> isset($param['nns_task_id'])?$param['nns_task_id']:null,
			'nns_task_name'=> isset($param['nns_task_name'])?$param['nns_task_name']:null,
			'nns_action'=>	$action,
			'nns_url' =>$file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Category,'.$action,
		);		
		return  self::execute_c2($c2_info,$sp_id);	
	}
	/**
	 * 增加内容栏目
	 * $category_info array(
	 * 'nns_category_id'
	 * 'nns_parent_id'
	 * 'nns_name'
	 * )
	 */
	static public function do_category($category_info,$action,$sp_id)
	{
		include_once dirname(dirname(__FILE__)).'/define.php';
		$sort = empty($category_info['nns_sort']) ? 0 : $category_info['nns_sort'];
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Category" ID="' .$category_info['nns_category_id']. '" Action="' . $action . '" Code="'.$category_info['nns_category_id'].'" ';		
		if(empty($category_info['nns_parent_id']) || !isset($category_info['nns_parent_id']))
		{
			$parent_id = 0;
		}
		else 
		{
			$parent_id = $category_info['nns_parent_id'];
		}
		$xml_str .= 'ParentCode="'.$parent_id.'" ParentID="'.$parent_id.'">';
		$xml_str .= '<Property Name="Name">'.$category_info['nns_name'].'</Property>';
		$xml_str .= '<Property Name="ParentID">'.$parent_id.'</Property>';
		$xml_str .= '<Property Name="Sequence">'.$sort.'</Property>';
		$xml_str .= '<Property Name="Status">1</Property>';
		$xml_str .= '<Property Name="Description"></Property>';
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
	
		$file_name = 'category_'.$category_info['nns_category_id'].'_'.$action.'.xml';

		
		$c2_info = array(
			'nns_task_type'=>'Category',
			'nns_task_id'=> isset($category_info['nns_task_id'])?$category_info['nns_task_id']:null,
			'nns_task_name'=> isset($category_info['nns_task_name'])?$category_info['nns_task_name']:null,
			'nns_action'=>	$action,
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
	
			'nns_desc' => 'Category,'.$action,
		);		
		return self::execute_c2($c2_info,$sp_id);
	}
	/**
	 * 执行C2注入命令
	 * @param $c2_info array(
	 * 			'c2_id'
	 * 			'file_name'
	 * 			'xml_content'
	 * )
	 */
	static public function execute_c2($c2_info,$sp_id)
	{
		$db = nn_get_db(NL_DB_WRITE);
		$db_r = nn_get_db(NL_DB_READ);
		$sp_config = sp_model::get_sp_config($sp_id);
		include_once dirname(dirname(dirname(dirname(__FILE__)))).'/mgtv/'.$sp_id.'/'.$sp_id.'_client.php';
		$c2_id = np_guid_rand();
		if(!self::exists_c2_commond($c2_info,$sp_id))
		{
			$sub_path = date('Y-m-d');
			$file = $c2_info['nns_url'];
			$c2_info['nns_url'] = $sub_path.'/'.$file;
			$xml_str = $c2_info['nns_content'];
			$file_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/'.$sp_id.'/inject_xml/'.$sub_path.'/';
			if(!is_dir($file_path)) 
			{
				mkdir($file_path,0777,true);
			}
			$file_path .= $file;
			file_put_contents($file_path,$xml_str);
			$CmdFileURL = C2_FTP . '/' .$c2_info['nns_url'];	
			$c2_info['nns_id'] = $c2_id;
			
			try {
				//CDN单日志模式开启
				if($sp_config['cdn_single_log_mode']=='0')
				{
					$exist_result = self::check_task_log_is_exist($c2_info['nns_task_id'],$c2_info['nns_action'],$db_r);
					if(is_array($exist_result) && !empty($exist_result))
					{
						$c2_id = $exist_result[0]['nns_id'];
						$c2_info['nns_id'] = $c2_id;
						$c2_info['nns_notify_fail_reason'] = '';
						$c2_info['nns_cdn_send_time'] = $exist_result[0]['nns_cdn_send_time']+1;
						$c2_info['nns_create_time'] = $exist_result[0]['nns_create_time'];
						$c2_info['nns_notify_content'] = "";
						self::update_c2_log($c2_info,$sp_id);
						self::update_c2_log_is_null(array('nns_result','nns_notify_result_url','nns_notify_result'),array('nns_id'=>$c2_info['nns_id']),$db);
						nn_log::write_log_message(LOG_MODEL_CDN, 'CDN单日志C2_LOG信息'.var_export($c2_info,true), $sp_id);
					}
				}
				np_runtime_ex($c2_id,false);
				$result = call_user_func_array(array($sp_id.'_client', 'ExecCmd'), array($c2_id, $CmdFileURL));
				$c2_info['nns_result'] = '['.$result->Result.']';			
				$bool = false;
				if($result->Result != 0 )
				{
					$c2_info['nns_result'] = '[-1]'.$result->ErrorDescription;
					//$c2_info['nns_notify_result'] = -1;
					$bool = true;
				}
				DEBUG && i_write_log_core('---------execute soap time----------'.np_runtime_ex($c2_id,true),'soap');
				DEBUG && i_write_log_core('---------execute soap time----------'.var_export($result,true),'soap');
				if($sp_config['cdn_single_log_mode']=='0' && is_array($exist_result) && !empty($exist_result))
				{
//                    self::update_c2_state('5',$c2_info['nns_task_id'],$db);
					self::update_c2_log($c2_info,$sp_id);
				}
				else
				{
					self::save_c2_log($c2_info,$sp_id);
				}
				if($bool)
				{
					return false;
				}
				return true;
			}
			catch (Exception $e)
			{
				DEBUG && i_write_log_core(var_export($e,true),$sp_id.'/c2');
				$c2_info['nns_result'] = '[-1]网络错误';
				//$c2_info['nns_notify_result'] = -1;
				self::save_c2_log($c2_info,$sp_id);
				return false;
			}		
		}
		return false;
		
	}	
	static public function exists_c2_commond($c2_info,$sp_id)
	{
		set_time_limit(0);
    	$db_r = nn_get_db(NL_DB_READ);
    	$nns_org_id = $sp_id;
    	$nns_task_type = $c2_info['nns_task_type'];
    	$nns_task_id = $c2_info['nns_task_id'];
    	$nns_action = $c2_info['nns_action'];	
		if(empty($nns_task_id)) 
		{
			return false;
		}		
		usleep(5000);
		//检查一小时前 是否有成功发送且相同的任务未返回结果
    	$sql = "select 1 from nns_mgtvbk_c2_log where nns_org_id='$nns_org_id' and nns_task_type='$nns_task_type' and nns_task_id='$nns_task_id' and nns_action='$nns_action' and nns_result = '[0]' and nns_notify_result is null and nns_create_time > NOW() - INTERVAL 3600 SECOND";
    	$data = nl_db_get_all($sql,$db_r);	
    	if(is_array($data) && count($data) > 0)
    	{
    		return true;
    	}
    	return false;
    }
	/**
	 * 保存C2命令日志
	 * $c2_log array(
	 * 			'nns_id',
	 * 			'nns_type',
	 * 			'nns_org_id',
	 * 			'nns_video_id',
	 * 			'nns_video_type',
	 * 			'nns_video_index_id',
	 * 			'nns_media_id',
	 * 			'nns_url',
	 * 			'nns_content',
	 * 			'nns_result',
	 * 			'nns_desc',
	 * 			'nns_create_time'
	 * )
	 */
	static public function save_c2_log($c2_log,$sp_id)
	{
		$db = nn_get_db(NL_DB_WRITE);
		$c2_log['nns_type'] = 'std';
		$c2_log['nns_org_id'] = $sp_id;
		$dt = date('Y-m-d H:i:s');
		$c2_log['nns_create_time'] = $dt;
		$c2_log['nns_send_time'] = $dt;
		return nl_db_insert($db,'nns_mgtvbk_c2_log',$c2_log);
	}
	/**
	 * C2通知命令日志
	 * $c2_notify array(
	 * 'nns_id',
	 * 'nns_notify_result_url',
	 * 'nns_notify_result',
	 * )
	 */
	static public function save_c2_notify_child($c2_notify)
	{				
		$db = nn_get_db(NL_DB_WRITE);
		$db_r = nn_get_db(NL_DB_READ);
		$dt = date('Y-m-d H:i:s');
		$wh_content ="";
		if($c2_notify['nns_notify_result'] != '-1')
		{
			$wh_content = "nns_content='',";
		}
		$sql = "update nns_mgtvbk_c2_log set " .
				"nns_notify_result_url='".$c2_notify['nns_notify_result_url']."' ," .$wh_content.
				"nns_notify_result='".$c2_notify['nns_notify_result']."', nns_notify_time='".$dt."'," .
				"nns_modify_time='".$dt."' " .
				"where nns_id='".$c2_notify['nns_id']."'";
		nl_execute_by_db($sql,$db);
	
		$sql = "select * from nns_mgtvbk_c2_log where nns_id='".$c2_notify['nns_id']."'";
		$c2_info = nl_db_get_one($sql,$db_r);
		$sp_config = sp_model::get_sp_config($c2_info['nns_org_id']);
		//如果回馈的消息是重发的消息
		if($sp_config['cdn_single_log_mode'] != '0')
		{
			if($c2_info == false || $c2_info['nns_again'] >= 1)
			{
				return false;
			}
		}
		nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, 'C2_NOTIFY：'.var_export($c2_notify,true), $c2_info['nns_org_id']);
		
		if($c2_info['nns_task_type'] == 'Series' || $c2_info['nns_task_type'] == 'Program' || $c2_info['nns_task_type'] == 'Movie')
		{
			if($c2_notify['nns_notify_result'] == '0')
			{				
				$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
				//是否需要异步获取播放穿				
				$cdn_query_mediaurl_bool = false;
				if(isset($sp_config['cdn_query_mediaurl']) && (int)$sp_config['cdn_query_mediaurl'] === 1)
				{
					$cdn_query_mediaurl_bool = true;
				}				
				if($cdn_query_mediaurl_bool && $c2_info['nns_task_type']=='Movie')
				{
					
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=6,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
					$sql_info = "select * from nns_mgtvbk_c2_task where nns_id='{$c2_info['nns_task_id']}'";
					$c2__taskinfo = nl_db_get_one($sql_info,$db_r);
					
					if(is_array($c2__taskinfo))
					{
						if($c2__taskinfo['nns_status'] == '0')
						{
							$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
						}
					}				
					if($c2_info['nns_action'] == 'DELETE')
					{
						$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
					}
				}
			}
			else 
			{
				$sql_update = "update nns_mgtvbk_c2_task set nns_status=-1,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";//注入媒体时，再次发送；否则媒体注入没有绑定节目					
			}
			nl_execute_by_db($sql_update,$db);	
		}
		//如果是片源且开启了播控切片
		if($c2_info['nns_task_type'] == 'Movie' && (int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
		{			
			$sql_c2_task = nl_db_get_one("select * from  nns_mgtvbk_c2_task  where nns_id='".$c2_info['nns_task_id']."'", $db);
			if($c2_info['nns_action']=='DELETE')
			{
				if($c2_notify['nns_notify_result'] != '0')
				{
					$nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_FAIL;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_FAIL];		
				}
				else
				{
					$nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_SUCC;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_SUCC];					
				}
			}
			else
			{
				if($c2_notify['nns_notify_result'] != '0')
				{
					$nns_state = clip_task_model::TASK_C_STATE_C2_FAIL;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_FAIL];	
				}
				else
				{
					$nns_state = clip_task_model::TASK_C_STATE_C2_SUCC;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_SUCC];					
				}
			}
				
			//更改切片状态
			$dt = date('Y-m-d H:i:s');
			$set_state = array(
				'nns_state' => $nns_state,
				'nns_desc' => $nns_desc,
				'nns_modify_time'=>$dt,
			);
			clip_task_model::update_task($sql_c2_task['nns_clip_task_id'], $set_state);
			//任务日志	
			$task_log = array(
				'nns_task_id' => $sql_c2_task['nns_clip_task_id'],
				'nns_state' => $nns_state,
				'nns_desc' => $nns_desc,
			);	
			clip_task_model::add_task_log($task_log);
		}
		//通知列队
		if($c2_notify['nns_notify_result'] == '0' && !empty($c2_info['nns_task_id']))
		{
			include_once dirname(dirname(dirname(__FILE__))).'/models/queue_task_model.php';
			$queue_task_model = new queue_task_model();
			$queue_task_model->q_report_task($c2_info['nns_task_id']);
			$queue_task_model = null;
		}
		
		//下载结果
		if(!empty($c2_notify['nns_notify_result_url']) && $c2_notify['nns_notify_result_url']!=='NULL')
		{
			if(!empty($c2_info['nns_task_id']))
			{
				$sql_info = "select * from nns_mgtvbk_c2_task where nns_id='{$c2_info['nns_task_id']}'";
				$c2_taskinfo = nl_db_get_one($sql_info,$db_r);
			}
			$url_arr = parse_url($c2_notify['nns_notify_result_url']);
			$port = isset($url_arr["port"])?$url_arr["port"]:21;
			include_once NPDIR . '/np_ftp.php';
			include_once NPDIR . '/np_xml2array.class.php';
			$ftp1=new nns_ftp($url_arr['host'],$url_arr["user"],$url_arr["pass"],$port);
			$ftpcon1=$ftp1->connect();
            if (empty($ftpcon1))
            {
            	nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, 'C2_NOTIFY：FTP链接失败', $c2_info['nns_org_id']);
				$sql_log = "update nns_mgtvbk_c2_log set nns_notify_result='-1',nns_notify_fail_reason='FTP链接失败' where nns_id='".$c2_notify['nns_id']."'";
				nl_execute_by_db($sql_log,$db);
				if(!empty($c2_info['nns_task_id']))
				{
					//添加失败次数
					$c2_taskinfo['nns_cdn_fail_time'] = $c2_taskinfo['nns_cdn_fail_time']+1;
					$sql_c2 = "update nns_mgtvbk_c2_task set nns_cdn_fail_time=".$c2_taskinfo['nns_cdn_fail_time']." where nns_id='".$c2_info['nns_task_id']."'";
					nl_execute_by_db($sql_c2,$db);
					if($sp_config['cdn_fail_retry_mode'] == '0' && $c2_taskinfo['nns_cdn_fail_time'] <= $sp_config['cdn_fail_retry_time'])
					{
						$sql_c2 = "update nns_mgtvbk_c2_task set nns_status='1' where nns_id='".$c2_info['nns_task_id']."'";
						$result = nl_execute_by_db($sql_c2,$db);
						if(!$result)
						{
							nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, 'C2_NOTIFY：FTP链接失败后修改C2状态失败', $c2_info['nns_org_id']);
						}
					}
				}
				return FALSE;
            }
            $notify_save_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/'.$c2_info['nns_org_id'].'/notify'.$url_arr["path"];
            $path_parts = pathinfo($notify_save_path);
            if (!is_dir($path_parts['dirname']))
            {
            	mkdir($path_parts['dirname'], 0777, true);
            }            
            $rs = $ftp1->get($url_arr["path"],$notify_save_path);
            if($rs == false)
            {
            	nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, 'C2_NOTIFY：下载 notify文件失败', $c2_info['nns_org_id']);
            	
				$sql_log = "update nns_mgtvbk_c2_log set nns_notify_result='-1',nns_notify_fail_reason='下载notify文件失败' where nns_id='".$c2_notify['nns_id']."'";
				nl_execute_by_db($sql_log,$db);
				if(!empty($c2_info['nns_task_id']))
				{
					//添加失败次数
					$c2_taskinfo['nns_cdn_fail_time'] = $c2_taskinfo['nns_cdn_fail_time']+1;
					$sql_c2 = "update nns_mgtvbk_c2_task set nns_cdn_fail_time=".$c2_taskinfo['nns_cdn_fail_time']." where nns_id='".$c2_info['nns_task_id']."'";
					nl_execute_by_db($sql_c2,$db);
					if($sp_config['cdn_fail_retry_mode'] == '0' && $c2_taskinfo['nns_cdn_fail_time'] <= $sp_config['cdn_fail_retry_time'])
					{
						$sql_c2 = "update nns_mgtvbk_c2_task set nns_status='1' where nns_id='".$c2_info['nns_task_id']."'";
						$result = nl_execute_by_db($sql_c2,$db);
						if(!$result)
						{
							nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, 'C2_NOTIFY：下载 notify文件失败后修改C2状态失败', $c2_info['nns_org_id']);
						}
					}
				}
				return FALSE;
            }
		}	
		return true;
	}		
	static  public function check_ftp_file($url,$sp_config)
	{
		$url_arr = parse_url($url);
		if(isset($sp_config['cdn_check_ts_accord_address']) && !empty($sp_config['cdn_check_ts_accord_address']))
		{
			$url_arr = parse_url($sp_config['cdn_check_ts_accord_address']);
		}
		$port = isset($url_arr["port"]) ? $url_arr["port"] : 21;
		$time = 10;
		$connect_no=ftp_connect($url_arr['host'],$port,$time);
		if ($connect_no===FALSE) return self::return_desc(1,'ftp连接失败');
		
		@ftp_login(
		$connect_no,
		$url_arr["user"],
		$url_arr["pass"]
		);
		//吉林联通要开启被动模式
		//重庆有线内网检测地址和华为下载地址不一致
		if(empty($sp_config['cdn_check_ts_accord_address']))
		{
			@ftp_pasv($connect_no,true);
		}
		//获取目录
		$path = str_replace("//","/",$url_arr['path']);
		$path_arr = explode("/",$path);
		array_pop($path_arr);
		$url_arr['path'] = implode("/",$path_arr);
		
		$check_int = 1;
		for ($i=1;$i<=3;$i++)
		{
			$contents = @ftp_nlist($connect_no, $url_arr['path']);
			if($contents===false)
			{
				continue;			
			}
			else
			{		
				$check_int = 2;
				//判断文件列表中是否有该文件<author:feijian.gao date:2017-1-19 11:18:13> --->start
				if(is_array($contents) && !empty($contents))
				{
					$check_int = 3;	
					break;
				}
				continue;			
				//--->end
			}
		}
		unset($connect_no);
		if($check_int === 1)
		{
			return self::return_desc(3,'获取文件列表失败');
		}
		elseif ($check_int === 2)
		{
			return self::return_desc(2,'文件不存在');
		}
		else 
		{
			return self::return_desc(0,'文件存在');
		}
	}

	public static function return_desc($ret, $desc=null)
	{
		$arr_return = array(
			'ret' => $ret,
			'reason' => $desc,
		);
		return $arr_return;
	}

	/**
	 * 检测该任务是否执行过
	 * @param $task_id
	 * @param $db
	 * @return bool
	 */
	static public function check_task_log_is_exist($task_id,$action,$db)
	{
		$time = date('Y-m-d');
		$sql = "select * from nns_mgtvbk_c2_log where nns_task_id='".$task_id."' and nns_action='".$action."' order by nns_create_time desc limit 1";
		return nl_query_by_db($sql,$db);
	}

	/**
	 * 更新CDN日志
	 * @param $c2_log
	 * @param $sp_id
	 * @return bool
	 */
	static public function update_c2_log($c2_log,$sp_id)
	{
		$db = nn_get_db(NL_DB_WRITE);
		$c2_log['nns_type'] = 'std';
		$c2_log['nns_org_id'] = $sp_id;
		$dt = date('Y-m-d H:i:s');
		$c2_log['nns_create_time'] = isset($c2_log['nns_create_time']) && !empty($c2_log['nns_create_time']) ? $c2_log['nns_create_time'] : $dt;
		$c2_log['nns_send_time'] = $dt;
		return nl_db_update($db,'nns_mgtvbk_c2_log',$c2_log,array('nns_id'=>$c2_log['nns_id']));
	}

	/**制空CDN日志字段
	 * @param $is_null_field
	 * @param null $where
	 * @param $db
	 * @return bool
	 */
	static public function update_c2_log_is_null($is_null_field,$where=null,$db)
	{
		if(is_array($is_null_field) && !empty($is_null_field))
		{
			foreach($is_null_field as $val)
			{
				$filed[] = $val."= null";
			}
		}
		else
		{
			return true;
		}
		$str = rtrim(implode(',',$filed),',');
		$wh = array();
		if (is_array($where)) {
			foreach ($where as $k => $v) {
				if (strpos($k, 'nns_') === FALSE)
					$k = 'nns_' . $k;
				$wh[] = "$k='$v'";
			}
			!empty($wh) && $where = implode(' and ', $wh);
		}
		if (is_string($where) && $where)
			$where = "where $where";
		$sql = "update nns_mgtvbk_c2_log set $str $where";
		return nl_execute_by_db($sql,$db);
	}


    /**
     * 更新CDN状态
     * @param $state
     * @param $task_id
     * @param $db
     * @return bool
     */
    static public function update_c2_state($state,$task_id,$db)
    {
        $sql = "update nns_mgtvbk_c2_task set nns_status = $state where nns_id ='".$task_id."'";
        return nl_execute_by_db($sql,$db);
    }
    /**
     * 注入program,movie绑定 不存在于播控平台的一个主媒资
     * @param $task_id 片源C2任务ID
     * @param $bind_vod_id 绑定的主媒资ID
     * @return boolean
     */
    static public function add_index_media_bind_vod($task_id,$bind_vod_id,$sp_id)
    {
    	include dirname(dirname(__FILE__)).'/define.php';
    	$dc = nl_get_dc(array(
		    'db_policy' =>  NL_DB_READ | NL_DB_WRITE,
		    'cache_policy' => NP_KV_CACHE_TYPE_NULL
		   )
		);
    	$sp_config = sp_model::get_sp_config($sp_id);
		//获取task任务
   		$c2_sql = "select * from nns_mgtvbk_c2_task where nns_id='{$task_id}'";
		$c2_task_info = nl_db_get_one($c2_sql, $dc->db());
		if (empty($c2_task_info) || $c2_task_info['nns_type'] != 'media')
		{
			return false;
		}
		//获取片源信息
		$media_id = $c2_task_info['nns_ref_id'];
		$video_media_info = video_model::get_vod_media_info($media_id);
		$result_media_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'media', $media_id,$video_media_info,$sp_config);
		if($result_media_import_info['ret'] !=0 || !isset($result_media_import_info['data_info']) || strlen($result_media_import_info['data_info']) <1)
		{
			return false;
		}
		$video_media_id = $result_media_import_info['data_info'];
		//获取分集信息
    	$video_index_info = video_model::get_vod_index_info($c2_task_info['nns_src_id']);
    	$result_index_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'index', $c2_task_info['nns_src_id'],$video_index_info,$sp_config);
    	if($result_index_import_info['ret'] !=0 || !isset($result_index_import_info['data_info']) || strlen($result_index_import_info['data_info']) <1)
    	{
    		return false;
    	}
    	$video_index_id = $result_index_import_info['data_info'];	
    	//获取主媒资信息
    	$video_info = video_model::get_vod_info($video_index_info['nns_vod_id']);
    	
    	$actor = str_replace(array('|',' ','/'), ',', $video_index_info['nns_actor']);
    	$director = str_replace(array('|',' ','/'), ',', $video_index_info['nns_director']);
    	$area = str_replace(array('|',' ','/'), ',', $video_info['nns_area']);
    	$language = str_replace(array('|',' ','/'), ',', $video_info['nns_language']);
    	$show_time = $video_index_info['nns_release_time'];
    	if((int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
    	{
    		$url = MOVIE_FTP . $c2_task_info['nns_file_path'];
    	}
    	else
    	{
    		if(strpos($video_media_info['nns_url'],'http://') === false || strpos($video_media_info['nns_url'],'ftp://') === false)
    		{
    			$url = rtrim(MOVIE_FTP,'/') . '/'. ltrim($video_media_info['nns_url'],'/');
    		}
    		else
    		{
    			$url = $video_media_info['nns_url'];
    		}
    	}
    	
    	$action = 'REGIST';
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
    	$xml_str .= '<Objects>';
    	$xml_str .= '<Object ElementType="Program" ID="' .$video_index_id. '" Action="' . $action . '" Code="' .$video_index_id. '">';
    	$xml_str .= '<Property Name="Name">'.htmlspecialchars($video_index_info['nns_name'],ENT_QUOTES).'HD</Property>';
    	$xml_str .= '<Property Name="OrderNumber"></Property>';//节目订购编号
    	$xml_str .= '<Property Name="OriginalName"></Property>';//原名
    	$xml_str .= '<Property Name="SortName"></Property>';//索引名称供界面排序
    	$xml_str .= '<Property Name="SearchName">'.$video_info['nns_pinyin'].'</Property>';//搜索名称供界面搜索
    	$xml_str .= '<Property Name="ActorDisplay">'.htmlspecialchars($actor,ENT_QUOTES).'</Property>';//演员列表(只供显示)
    	$xml_str .= '<Property Name="WriterDisplay">'.htmlspecialchars($director,ENT_QUOTES).'</Property>';//作者列表(只供显示)
    	$xml_str .= '<Property Name="OriginalCountry">'.htmlspecialchars($area,ENT_QUOTES).'</Property>';//国家地区
    	$xml_str .= '<Property Name="Language">'.htmlspecialchars($language,ENT_QUOTES).'</Property>';//语言
    	$xml_str .= '<Property Name="ReleaseYear">' .  date('Y',strtotime($show_time)).'</Property>';//上映年份(YYYY)
    	$xml_str .= '<Property Name="OrgAirDate">' . date('Ymd',strtotime($show_time)).'</Property>';//首播日期(YYYYMMDD)
    	$xml_str .= '<Property Name="LicensingWindowStart">'. date('YmdHis').'</Property>';//有效开始时间(YYYYMMDDHH24MiSS)
    	$xml_str .= '<Property Name="LicensingWindowEnd">'. date('YmdHis',time()+ 3*365*24*60*60).'</Property>';//有效结束时间(YYYYMMDDHH24MiSS)
    	$xml_str .= '<Property Name="DisplayAsNew">0</Property>';//新到天数
    	$xml_str .= '<Property Name="DisplayAsLastChance">300</Property>';//剩余天数
    	$xml_str .= '<Property Name="Macrovision">0</Property>';//拷贝保护标志0:无拷贝保护	1:有拷贝保护
    	$xml_str .= '<Property Name="Description">'.mb_substr(htmlspecialchars($video_index_info['nns_summary'],ENT_QUOTES),0,400,'utf-8').'</Property>';//描述信息
    	$xml_str .= '<Property Name="PriceTaxIn"></Property>';//列表定价
    	$xml_str .= '<Property Name="Status">1</Property>';//状态标志 0:失效 1:生效
    	$xml_str .= '<Property Name="SourceType">1</Property>';//1: VOD 5: Advertisement
    	$xml_str .= '<Property Name="SeriesFlag">1</Property>';//0: 普通VOD 1: 连续剧剧集
    	$xml_str .= '<Property Name="Kpeople">'.htmlspecialchars($actor,ENT_QUOTES).'</Property>';//关键字 多个关键字之间使用分号分隔
    	$xml_str .= '<Property Name="Director">'.htmlspecialchars($director,ENT_QUOTES).'</Property>';//关联标签 多个标签之间使用分号分隔
    	$xml_str .= '<Property Name="ScriptWriter"></Property>';//编剧
    	$xml_str .= '<Property Name="Guest"></Property>';//受访者
    	$xml_str .= '<Property Name="Reporter"></Property>';//记者
    	$xml_str .= '<Property Name="OPIncharge"></Property>';//其他责任人
    	$xml_str .= '<Property Name="Compere"></Property>';//节目主持人
    	$xml_str .= '</Object>';
    	if(!empty($video_index_info['nns_image']))
    	{
    		$img_save_name = str_replace('.JPG','.jpg',$video_index_info['nns_image']);
    		$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
    		if(file_exists($file_img))
    		{
    			$pic_url = self::get_image_url($img_save_name,$sp_id);
    			$xml_str .= '<Object ElementType="Picture" ID="' .$video_index_id. '" Action="' . $action . '" Code="' .$video_index_id. '">';
    			$xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
    			$xml_str .= '<Property Name="Description"></Property>';//描述
    			$xml_str .= '</Object>';
    		}
    	}	
    	$xml_str .= '<Object ElementType="Movie" ID="' .$video_media_id. '" Action="' . $action . '" Code="' .$video_media_id. '" >';
    	$xml_str .= '<Property Name="Type">1</Property>';//媒体类型1:正片 2:预览片
    	$xml_str .= '<Property Name="FileURL">' .$url. '</Property>';//媒体文件URL,ftp://username:password@ip:port/...  标准FTP协议
    	$xml_str .= '<Property Name="SourceDRMType">0</Property>';//0: No DRM 1: BES DRM
    	$xml_str .= '<Property Name="DestDRMType">0</Property>';//
    	$xml_str .= '<Property Name="AudioType">1</Property>';//0: 其他 1: Monaural 单声道 2: Stereo 多声道 3: Two-nation monaural 双单声道 4: Two-nation stereo 双多声道  5: AC3(5:1 channel) AC3声道
    	$xml_str .= '<Property Name="ClosedCaptioning">1</Property>';//0:无字幕 1:有字幕
    	$xml_str .= '<Property Name="ScreenFormat"></Property>';
    	$xml_str .= '</Object>';
    	
    	$xml_str .= '</Objects>';
    			
    	$xml_str .= '<Mappings>';
    	
    	$sequence = $video_index_info['nns_index'] + 1;
    	$xml_str .= '<Mapping ParentType="Series" ParentID="'.$bind_vod_id.'" ElementType="Program" ElementID="'.$video_index_id.'" ParentCode="'.$bind_vod_id.'" ElementCode="'.$video_index_id.'" Action="'.$action.'">';
    	$xml_str .= '<Property Name="Sequence">'.$sequence.'</Property>';//
    	$xml_str .= '</Mapping>';   		
    	if(!empty($video_index_info['nns_image']))
    	{
    		$img_save_name = str_replace('.JPG','.jpg',$video_index_info['nns_image']);
    		$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
    		if(file_exists($file_img))
    		{
    			$xml_str .= '<Mapping ParentType="Picture" ParentID="'.$vod_index_id.'" ElementType="Program" ElementID="'.$vod_index_id.'" ParentCode="'.$vod_index_id.'" ElementCode="'.$vod_index_id.'" Action="' . $action . '">';
    			//Picture时：0: 缩略图 1: 海报 2: 剧照 3: 图标 4: 标题图 5: 广告图 6: 草图 7: 背景图 9: 频道图片
    			//10: 频道黑白图片 11: 频道Logo 12: 频道名字图片99: 其他
    			$xml_str .= '<Property Name="Type">1</Property>';
    			$xml_str .= '<Property Name="Sequence">0</Property>';
    			$xml_str .= '</Mapping>';
    		}
    	}
    	$xml_str .= '<Mapping ParentType="Program" ParentID="'.$video_index_id.'" ElementType="Movie" ElementID="'.$video_media_id.'" ParentCode="'.$video_index_id.'" ElementCode="'.$video_media_id.'" Action="'.$action.'">';
    	$xml_str .= '</Mapping>';
    	$xml_str .= '</Mappings>';
    	$xml_str .= '</ADI>';
    			
    	//die($xml_str);    		
    	$file_name = "program_movie_{$video_media_id}_bind_{$bind_vod_id}_{$action}.xml";
    	$c2_info = array(
    			'nns_task_type'=>'Movie',
    			'nns_task_id'=> $task_id,
    			'nns_task_name'=> isset($c2_task_info['nns_name'])?$index_media['nns_name']:null,
    			'nns_action'=>	$action,
    			'nns_url' => $file_name,
    			'nns_content' => $xml_str,
    			'nns_desc' => 'Movie,'.$action,
    	);
    	return self::execute_c2($c2_info,$sp_id);
    }
    /**
     * 注入主媒资与分集的绑定关系
     * @param $bind_vod_id 绑定的主媒资ID
     * @param $bind_index_ids 绑定的分集ID,多个以逗号分隔
     * @param $sp_id SPID
     * @return boolean
     */
    static public function add_index_bind_vod($bind_vod_id,$bind_index_ids,$sp_id)
    {
    	$action = 'REGIST';
    	$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
    	$xml_str .= '<Mappings>';
    	$ids_arr = explode(",", $bind_index_ids);
    	$map_str = '';
    	foreach ($ids_arr as $id)
    	{
    		if(empty($id))
    		{
    			continue;
    		}
	    	$map_str .= '<Mapping ParentType="Series" ParentID="'.$bind_vod_id.'" ElementType="Program" ElementID="'.$id.'" ParentCode="'.$bind_vod_id.'" ElementCode="'.$id.'" Action="'.$action.'">';
	    	//$xml_str .= '<Property Name="Sequence">'.$bind_index.'</Property>';//
	    	$map_str .= '</Mapping>';
    	}
    	if(empty($map_str))
    	{
    		return false;
    	}
    	$xml_str .= $map_str;
    	$xml_str .= '</Mappings>';
    	$xml_str .= '</ADI>';
    	$guid = np_guid_rand();
	    $file_name = "Maping_{$guid}_bind_{$bind_vod_id}_{$action}.xml";
	    $c2_info = array(
	    		'nns_task_type'=>'Maping',
	    		'nns_task_id'=> '',
	    		'nns_task_name'=> '',
	    		'nns_action'=>	$action,
	    		'nns_url' => $file_name,
	    		'nns_content' => $xml_str,
	    		'nns_desc' => 'Maping,'.$action,
	    );
	    return self::execute_c2($c2_info,$sp_id);
	}
}
